<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="工厂" prop="factory">
        <el-select
          v-model="queryParams.factory"
          placeholder="请选择"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('factory')"
        >
          <el-option
            v-for="(item, index) in factoryOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工段" prop="workshopCode">
        <el-select
          v-model="queryParams.workshopCode"
          placeholder="请选择工段"
          clearable
          filterable
          style="width: 240px"
          @change="handleSearchListChange('workSection')"
        >
          <el-option
            v-for="(item, index) in workshopOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产线" prop="lineCode">
        <el-select
          v-model="queryParams.lineCode"
          placeholder="请选择产线"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('productLine')"
        >
          <el-option
            v-for="(item, index) in lineOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工艺段" prop="sectionCode">
        <el-select
          v-model="queryParams.sectionCode"
          placeholder="请选择工艺段"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('sectionCode')"
        >
          <el-option
            v-for="(item, index) in processOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入产品名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="投料批号" prop="feedingBatchNo">
        <el-input
          v-model="queryParams.feedingBatchNo"
          placeholder="请输入投料批号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产出批号" prop="outputBatchNo">
        <el-input
          v-model="queryParams.outputBatchNo"
          placeholder="请输入产出批号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="投料时间段" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          style="width: 240px"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="收卷时间段" prop="date">
        <el-date-picker
          v-model="queryParams.date1"
          style="width: 240px"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="(item, index) in report_work_status"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <!-- <el-button type="primary" icon="Edit" @click="handleSuccession"
          v-hasPermi="['prod:changeShift:succession']"
            >接班</el-button
          > -->
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="typeList"
      border
      style="width: 100%"
      max-height="500px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column width="100" label="生产日期" prop="prodDate" />
      <el-table-column width="100" label="班次" prop="classesName" />
      <el-table-column
        label="班组"
        prop="workGroupName"
        :show-overflow-tooltip="true"
        width="140"
      ></el-table-column>
      <el-table-column width="100" label="订单编号" prop="orderCode" />
      <el-table-column width="100" label="生产产品" prop="prodName" />
      <el-table-column width="100" label="投料内容" prop="matName" />
      <el-table-column width="140" label="投料批号" prop="feedingBatchNo">
        <template #default="scope">
          <el-link
            v-hasPermi="['produce:ProdReportWork:query']"
            type="primary"
            @click="goDetailFeeding(scope.row)"
          >
            {{ scope.row.feedingBatchNo || "-" }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column width="100" label="投入数量" prop="inputQty" />
      <el-table-column width="100" label="单位" prop="inputUnit" />
      <el-table-column width="100" label="投料时间" prop="feedingTime" />
      <el-table-column width="100" label="收卷时间" prop="rollingTime" />
      <el-table-column width="140" label="产出批号" prop="outputBatchNo">
        <template #default="scope">
          <el-link type="primary" @click="handleUpdate(scope.row, 'view')">
            {{ scope.row.status == "9" ? "无" : scope.row.outputBatchNo || "-" }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column width="100" label="产出数量" prop="outputQyt" />
      <el-table-column width="100" label="有效数量" prop="effectiveQyt" />
      <el-table-column width="100" label="损耗" prop="loss" />
      <!-- <el-table-column width='100' label="良率" prop="monitorName" /> -->
      <el-table-column width="100" label="投产比" prop="inputProdRate">
        <template #default="scope">
          <span v-if="scope.row.inputProdRate">{{ scope.row.inputProdRate }}%</span>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column width="100" label="缺陷描述" prop="defectDesc" />
      <el-table-column width="100" label="操作人" prop="operator" />
      <el-table-column width="100" label="记录时间" prop="recordTime" />

      <!-- <el-table-column width="100" label="质检结果" prop="testingResult" /> -->
      <el-table-column label="质检结果" prop="testingResult">
        <template #default="scope">
          <dict-tag
            v-if="scope.row.testingResult"
            :options="quality_testing_result"
            :value="scope.row.testingResult"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column width="100" label="外观判定" prop="appearanceJudgment" />
      <el-table-column width="100" label="性能判定" prop="performanceJudgment" />
      <el-table-column width="100" label="不良描述" prop="qmsDefectDesc" />

      <el-table-column width="100" label="工厂" prop="factoryName" />
      <el-table-column width="100" label="工段" prop="workshopName" />
      <el-table-column width="100" label="产线" prop="productLineName" />
      <el-table-column width="100" label="工艺段" prop="sectionName" />
      <el-table-column width="100" label="状态" prop="status">
        <template #default="scope">
          <dict-tag :options="report_work_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <p>让我测试一下</p> -->
      <el-table-column
        label="操作"
        align="center"
        width="150"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- v-if="scope.row.status == 1" -->
          <!-- <el-button
              link
              type="primary"
              icon="Edit"
               v-hasPermi="['prod:changeShift:edit']"
              @click="handleUpdate(scope.row,'edit')"
              >编辑</el-button
            > -->
          <!-- 状态：1-待报工，2-待请检，3-质检中，4-待审核，5-审核通过，6-审核驳回，7-已重新报工 8 已分切复卷 -->
          <el-button
            link
            type="primary"
            icon="Edit"
            v-if="scope.row.status == 1"
            v-hasPermi="['produce:ProdReportWork:doReportWork']"
            @click="handleUpdate(scope.row, 'add')"
          >
            报工
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            v-if="scope.row.status == 1"
            v-hasPermi="['produce:ProdReportWork:returnMaterials2WH']"
            @click="handleUpdate(scope.row, 'returnMaterials')"
          >
            退料入仓
          </el-button>
          <!-- <el-button
              link
              type="primary"
              icon="Edit"
               v-hasPermi="['prod:changeShift:add']"
              @click="handleUpdate(scope.row,'QJ')"
              >请检</el-button
            > -->
          <el-button
            link
            type="primary"
            icon="Edit"
            v-if="scope.row.status == 4"
            v-hasPermi="['produce:ProdReportWork:audit']"
            @click="handleUpdate(scope.row, 'audit')"
          >
            审核
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            v-if="scope.row.status == 6"
            v-hasPermi="['produce:ProdReportWork:againReportWork']"
            @click="handleUpdate(scope.row, 'reapplyAdd')"
          >
            重新报工
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            v-if="scope.row.status == 6"
            v-hasPermi="['produce:ProdReportWork:againReportWork']"
            @click="handleUpdate(scope.row, 'FQFJ')"
          >
            分切复卷
          </el-button>
          <!-- <p v-if="['2', '3', '5', '7'].includes(scope.row.status)">-</p> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog v-model="returnMaterialsDialog" width="500">
      <!-- {退料数量}{产品单位} -->
      <span>
        确定将此投料剩余数量 {{ returnMaterialsData.remainingQuantity }}
        {{ returnMaterialsData.inputUnit }}原路退回至线边仓"{{
          returnMaterialsData.storehouseName
        }}"吗？
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="returnMaterialsDialog = false">取消</el-button>
          <el-button type="primary" @click="sureReturnMaterials()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="productionReport">
import { depeIdSelectList } from "@/api/system/dept";
import { listProdReportWork, returnMaterials2WH } from "@/api/productionMgt/productionReport";
import { getCurrentInstance, ref, reactive, toRefs, onMounted } from "vue";
import DataInfo from "./data";
import DataInfoFeeding from "./../productionFeeding/data.vue";
import { getFeeding } from "@/api/productionMgt/feeding";
import { floatAdd, floatSub } from "@/utils/mathCount";
const { proxy } = getCurrentInstance();
const typeList = ref([]);
const { report_work_status } = proxy.useDict("report_work_status");
const { quality_testing_result } = proxy.useDict("quality_testing_result");
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
var factoryOptions = ref([]);
var workshopOptions = ref([]);
var lineOptions = ref([]);
var processOptions = ref([]);
const returnMaterialsDialog = ref(false);
const returnMaterialsData = reactive({
  remainingQuantity: 0,
  storehouseName: "",
  inputUnit: "",
});
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: "1",
    name: undefined,
  },
});

const { queryParams } = toRefs(data);
/** 查询设备类型列表 */
function getList() {
  loading.value = true;
  let newForm = JSON.parse(JSON.stringify(queryParams.value));
  if (queryParams.value?.date?.length) {
    newForm.startFeedingTime = queryParams.value.date[0] + " 00:00:00";
    newForm.endFeedingTime = queryParams.value.date[1] + " 23:59:59";
    delete newForm.date;
  }
  if (queryParams.value?.date1?.length) {
    newForm.startRollingTime = queryParams.value.date1[0] + " 00:00:00";
    newForm.endRollingTime = queryParams.value.date1[1] + " 23:59:59";
    delete newForm.date;
  }
  listProdReportWork(proxy.addDateRange(newForm)).then((response) => {
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getFactorys() {
  // getFactoryTree(query).then((res) => {
  //   factoryOptions.value = res.data;
  // });
  depeIdSelectList({
    deptType: "factory",
    deptCode: "",
    permissionType: "permission",
  }).then((res) => {
    factoryOptions.value = res.data;
  });
}
/** 投料详情操作 */
function goDetailFeeding(row) {
  row.id = row.feedingId;
  proxy.subPage(
    DataInfoFeeding,
    { title: "投料详情", data: { ...row, parentType: "view" } },
    () => {
      getList();
    }
  );
}
function handleSearchListChange(type) {
  if (type == "factory") {
    depeIdSelectList({
      deptType: "station",
      deptCode: queryParams.value.factory,
      permissionType: "permission",
    }).then((res) => {
      workshopOptions.value = res.data;
      lineOptions.value = [];
      processOptions.value = [];
      queryParams.value.workshopCode = "";
      queryParams.value.lineCode = "";
      queryParams.value.sectionCode = "";
    });
  }
  if (type == "workSection") {
    depeIdSelectList({
      deptType: "line",
      deptCode: queryParams.value.workshopCode,
      permissionType: "permission",
    }).then((res) => {
      lineOptions.value = res.data;
      processOptions.value = [];
      queryParams.value.lineCode = "";
      queryParams.value.sectionCode = "";
    });
  }
  if (type == "productLine") {
    depeIdSelectList({
      deptType: "craft",
      deptCode: queryParams.value.lineCode,
      permissionType: "permission",
    }).then((res) => {
      processOptions.value = res.data;
      queryParams.value.sectionCode = "";
    });
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.date = [];
  queryParams.value.date1 = [];
  proxy.resetForm("queryRef");
  queryParams.value.status = "";
  handleQuery();
}
// 确定退料入仓
function sureReturnMaterials() {
  console.log(returnMaterialsData);
  returnMaterials2WH(returnMaterialsData.row.id).then(() => {
    returnMaterialsDialog.value = false;
    getList();
  });
}
// 点击退料入仓
function returnMaterials(row) {
  // <!-- 状态：1-待报工，2-待请检，3-质检中，4-待审核，5-审核通过，6-审核驳回，7-已重新报工 8 已分切复卷 -->
  let newForm = JSON.parse(JSON.stringify(queryParams.value));
  // 退料数量=投料数量-此班次此投料批号下的报工记录中产出数量之和；
  // 其中，此班次此投料批号下的报工记录中产出数量之和=根据投料ID查询“质检中、待审核、审核通过、审核驳回”状态的报工记录中产出数量之和；
  newForm.pageSize = 10000;
  newForm.status = "";
  newForm.statusList = "3,4,5,6";
  newForm.feedingId = row.feedingId;
  let inputQty = row.inputQty;
  let outputQyt = 0;
  listProdReportWork(proxy.addDateRange(newForm)).then((response) => {
    if (response.rows && response.rows.length) {
      inputQty = response.rows[0].inputQty;
      response.rows.forEach((item) => {
        outputQyt = floatAdd(outputQyt, item.outputQyt);
      });
    }
    getFeeding(row.feedingId).then((res) => {
      if (res.data) {
        returnMaterialsData.remainingQuantity = floatSub(inputQty, outputQyt);
        returnMaterialsData.storehouseName = res.data.storehouseName;
        returnMaterialsData.inputUnit = row.inputUnit;
        returnMaterialsData.row = row;
      }
    });
  });
  returnMaterialsDialog.value = true;
}
/** 修改按钮操作 */
function handleUpdate(row, type) {
  const title = {
    add: "报工",
    edit: "编辑报工",
    // 'BGSH':'报工审核',
    reapplyAdd: "重新报工",
    view: "报工详情",
    audit: "审核",
    returnMaterials: "退料入仓",
    FQFJ: "分切复卷",

    // 'QJ':'请检',
  };
  // 退料入仓  提示
  if (type == "returnMaterials") {
    returnMaterials(row);
    return;
  }
  if (!proxy.checkPermi(["produce:ProdReportWork:query"])) {
    return;
  }
  proxy.subPage(DataInfo, { title: title[type], data: { ...row, parentType: type } }, () => {
    getList();
  });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

getList();
getFactorys();
onMounted(async () => {
  getList();
});
</script>
